package com.wn.service.impl;

import com.wn.common.RedisConst;
import com.wn.mapper.BookMapper;
import com.wn.model.entity.Book;
import com.wn.model.vo.CartItemVo;
import com.wn.model.vo.CartVo;
import com.wn.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    BookMapper bookMapper;


    /**
     * 获取用户的购物车
     *
     * @param userId
     */
    @Override
    public CartVo getCart(Long userId) {
        //从Redis中获取用户的购物车
        ValueOperations<String, CartVo> ops = redisTemplate.opsForValue();
        CartVo cart = ops.get(RedisConst.USER_CART_PREFIX + ":" + userId);
        //如果Redis中没有，创建一个新的购物车
        if (cart == null) {
            cart = new CartVo();
            //添加用户的ID到购物车
            cart.setUserId(userId);
            //将数据存入Redis
            ops.set(RedisConst.USER_CART_PREFIX + ":" + userId, cart);
        }
        return cart;
    }

    /**
     * 添加一件商品到购物车
     *
     * @param userId
     * @param bookId
     */
    @Override
    public CartVo addCartItem(Long userId, Long bookId) {
        //获取某个用户的购物车对象
        CartVo cart = getCart(userId);
        //通过bookId从数据库中获取书籍对象
        Book book = bookMapper.selectById(bookId);
        //调用方法添加到购物车中，数量是1本
        CartItemVo item = new CartItemVo(userId,
                bookId,
                book.getName(),
                book.getImgSrc(),
                book.getPrice(), 1);
        cart.addItem(item);
        //将购物车对象保存到Redis中7天
        redisTemplate.opsForValue().set(
                RedisConst.USER_CART_PREFIX + ":" + userId,
                cart,
                RedisConst.USER_CART_EXPIRE, TimeUnit.DAYS);
        return cart;
    }

    @Override
    public CartVo removeCartItem(Long userId, Long bookId) {
        CartVo cart = getCart(userId);
        cart.removeItem(bookId);
        redisTemplate.opsForValue().set(
                RedisConst.USER_CART_PREFIX + ":" + userId,
                cart,
                RedisConst.USER_CART_EXPIRE, TimeUnit.DAYS);
        return cart;
    }

    @Override
    public CartVo clearCart(Long userId) {
        CartVo cart = getCart(userId);
        cart.clearCart();
        redisTemplate.opsForValue().set(
                RedisConst.USER_CART_PREFIX + ":" + userId,
                cart,
                RedisConst.USER_CART_EXPIRE, TimeUnit.DAYS);
        return cart;
    }
}
